package com.winter.mq;

import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.springframework.stereotype.Component;

/**
 * @author JinHao
 * Date: 2023/04/18 15:49
 */
@Slf4j
@Component
public class RocketMqProducer {
    private static final DefaultMQProducer PRODUCER;
    public static final String NAME_SERVICE_ADDRESS = "localhost:9876";

    static {
        log.info("RocketMQ producer 开始启动。。。");
        PRODUCER = new DefaultMQProducer("Producer-Group");
        PRODUCER.setNamesrvAddr(NAME_SERVICE_ADDRESS);
        try {
            PRODUCER.start();
            log.info("RocketMQ producer 完成启动。。。");
        } catch (MQClientException e) {
            log.error("RocketMQ producer 启动异常 e:", e);
        }
    }

    /**
     * 发送消息
     *
     * @param topic 主题
     * @param tag   标签
     * @param body  内容
     */
    public static void sendMessage(String topic, String tag, String body) {
        Message message = new Message(topic, tag, body.getBytes());
        try {
            SendResult result = PRODUCER.send(message);
            log.info("RocketMQ producer 发送完成 返回信息 receipt-{}-", result);
        } catch (Exception e) {
            log.error("RocketMQ producer 发送异常 异常信息e:", e);
        }
    }
}
